    //
//  VmixGridViewController.m
//  VMIX
//
//  Created by jeffs on 6/1/10.
//  Copyright 2010 Vmix Media, INC. All rights reserved.
//

#import "VmixGridViewController.h"
#import "VmixGridViewCell.h"
#import "VmixVideo.h"
#import "CollectionsPopOver.h"
#import "VmixCollection.h"
#import "VmixVideo.h"

enum
{
    VmixVideoCellTypePlain
};

@implementation VmixGridViewController
@synthesize mediasArray, video, imageCache, gridView, rightArrowButton, leftArrowButton, collectionsButton, collectionsList, collection, delegate, collectionsPopOver, collectionsPopOverView;
@synthesize collectionSpinner, oppQueue, getMediaListOperation;
/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	
    [super viewDidLoad];
	
	[self.navigationItem setHidesBackButton:YES animated:YES];
	self.navigationController.navigationBar.tintColor = [UIColor darkGrayColor];
	self.parentViewController.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_center_large_gray.png"]];
	//self.view.backgroundColor = [UIColor clearColor];


	
	self.collectionsButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
	self.collectionsButton.frame = CGRectMake(110.0, 360.0, 200.0, 30.0);
	[self.collectionsButton.titleLabel setFont:[UIFont boldSystemFontOfSize:14.0]];
    //[self.collectionsButton  setTitle:@"" forState:UIControlStateNormal];
    self.collectionsButton.backgroundColor = [UIColor clearColor];
    [self.collectionsButton  setTitleColor:[UIColor blackColor] forState:UIControlStateNormal ];
    UIImage *buttonImageNormal = [UIImage imageNamed:@"alternate_blue_button.png"];
   // UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
    [self.collectionsButton  setBackgroundImage:buttonImageNormal forState:UIControlStateNormal];
	[self.collectionsButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //UIImage *buttonImagePressed = [UIImage imageNamed:@"whiteButton.png"];
    //UIImage *strechableButtonImagePressed = [buttonImagePressed stretchableImageWithLeftCapWidth:12 topCapHeight:0];
	// [playButton setBackgroundImage:strechableButtonImagePressed forState:UIControlStateHighlighted];
    //[self.collectionsButton addTarget:self action:@selector(showCollections) forControlEvents:UIControlEventTouchUpInside];
	[self.collectionsButton addTarget:self action:@selector(showCollections) forControlEvents:UIControlEventTouchUpInside];
	self.navigationItem.titleView = self.collectionsButton;

	UIImage *arrowImg2 = [UIImage imageNamed:@"left_arrow.png"];
	UIButton * arrowButton2 = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
	arrowButton2.frame = CGRectMake(0, 0, 21, 30);
	arrowButton2.backgroundColor = [UIColor clearColor];
	[arrowButton2 setBackgroundImage:arrowImg2 forState:UIControlStateNormal];
	[arrowButton2 addTarget:self action:@selector(collapseView) forControlEvents:UIControlEventTouchUpInside];
	self.leftArrowButton = [[UIBarButtonItem alloc] initWithCustomView:arrowButton2];
	
	self.navigationItem.rightBarButtonItem = self.leftArrowButton ;
	
	self.collectionsPopOverView = [[[CollectionsPopOver alloc] init] autorelease];
	self.collectionsPopOverView.wheelSource = self.collectionsList;
	self.collectionsPopOverView.rootDelegate = self.delegate;
	//[self.collectionsButton  setTitle:self.collection.name forState:UIControlStateNormal];
	
	imageCache = [[NSMutableDictionary alloc] init];
    //self.gridView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
	self.gridView.autoresizesSubviews = YES;
	self.gridView.delegate = self;
	self.gridView.dataSource = self;
	self.gridView.separatorColor = [UIColor blueColor];


	
}


 - (void)viewWillAppear:(BOOL)animated {
 [super viewWillAppear:animated];
	 
	[self.collectionsButton  setTitle:self.collection.name forState:UIControlStateNormal]; 
	[self.gridView reloadData];
	 
 }
 



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Overriden to allow any orientation.
    return NO;
}

- (void) willRotateToInterfaceOrientation: (UIInterfaceOrientation) toInterfaceOrientation
duration: (NSTimeInterval) duration
{
    if ( UIInterfaceOrientationIsPortrait(toInterfaceOrientation) )
    {
        // width will be 768, which divides by four nicely already
        NSLog( @"Setting left+right content insets to zero" );
        _gridView.leftContentInset = 0.0;
        _gridView.rightContentInset = 0.0;
    }
    else
    {
        // width will be 1024, so subtract a little to get a width divisible by five
        NSLog( @"Setting left+right content insets to 2.0" );
        _gridView.leftContentInset = 2.0;
        _gridView.rightContentInset = 2.0;
    }
}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)fetchImage:(NSArray *)args {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    UIImageView *iv = [args objectAtIndex:0];
    NSString *str = [args objectAtIndex:1];
    NSURL *imageUrl = [NSURL URLWithString:str];
    NSURLRequest *imageReq = [NSURLRequest requestWithURL:imageUrl];
    NSURLResponse *response = nil;
    NSError *error = nil;
    NSData *imageData = [NSURLConnection sendSynchronousRequest:imageReq returningResponse:&response error:&error];
    UIImage *theImage = [UIImage imageWithData:imageData];
    [self.imageCache setObject:theImage forKey:str];
	// if (iv.tag == [[args objectAtIndex:2] intValue]) {
	[iv setImage:theImage];
	// }
    [pool release];
}

- (UIImage *)getImageForURL:(NSString *)str inImageView:(UIImageView *)iv {
    UIImage *i = nil;
    if ([self.imageCache objectForKey:str] != nil) {
        i = [self.imageCache objectForKey:str];
    } else {
        i = [[UIImage alloc] init];
        NSArray *args = [NSArray arrayWithObjects:iv, str, [NSNumber numberWithInt:iv.tag], nil];
        [self performSelectorInBackground:@selector(fetchImage:) withObject:args];
		
    }
    return i;
}


#pragma mark -
#pragma mark Grid View Data Source

- (NSUInteger) numberOfItemsInGridView: (AQGridView *) aGridView
{
    return ( [self.mediasArray count] );
}

- (AQGridViewCell *) gridView: (AQGridView *) aGridView cellForItemAtIndex: (NSUInteger) index
{
			static NSString * PlainCellIdentifier = @"PlainCellIdentifier";
			AQGridViewCell * cell = nil;
	
			if(self.video== nil){
				VmixVideo *v = [[VmixVideo alloc] init];
				self.video = v;
			}
			self.video = [self.mediasArray objectAtIndex:index];
			
			
            VmixGridViewCell * plainCell = (VmixGridViewCell *)[aGridView dequeueReusableCellWithIdentifier: PlainCellIdentifier];
            if ( plainCell == nil )
            {
                plainCell = [[[VmixGridViewCell alloc] initWithFrame: CGRectMake(0.0, 0.0, 200.0, 230.0)
														  reuseIdentifier: PlainCellIdentifier] autorelease];
				plainCell.selectionStyle = AQGridViewCellSelectionStyleBlue;

            }
	
	
	NSString *path = self.video.thumbnail;
	NSString *imgMan = [NSString stringWithFormat:@"http://cdn-aki.vmixcore.com/imgman.jpg?fill=000000000&url=%@&width=190&height=145", path];
	//plainCell.imageView.tag= index + 1000;
	//plainCell.imagePath = imgMan;
	plainCell.title.text = self.video.title;
	plainCell.description.text = self.video.description;
	plainCell.imageView.tag = index + 1000;
	plainCell.imageView.image = [self getImageForURL:imgMan inImageView:plainCell.imageView];
	cell = plainCell;

    
    return ( cell );
	
}

/**
 * handle collapseView
 */
- (void) collapseView {
	
	[self.delegate collapseView];
	
}

- (void) gridView: (AQGridView *) gridView didSelectItemAtIndex: (NSUInteger) index{
	
	VmixVideo *v = (VmixVideo *) [self.mediasArray objectAtIndex:index];
	[self.delegate.detailViewController loadVideo:v];
	
	[self collapseView];
}

- (CGSize) portraitGridCellSizeForGridView: (AQGridView *) aGridView
{
    return ( CGSizeMake(224.0, 230.0) );
}

- (void)showCollections{


	self.collectionsPopOver = [[[UIPopoverController alloc] 
								initWithContentViewController:self.collectionsPopOverView] autorelease];               
	
	[self.collectionsPopOver presentPopoverFromRect:self.collectionsButton.frame inView:self.navigationController.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
	
}


-(void) getMediaListForCollection:(VmixCollection *) theCollection{
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
	self.collectionSpinner.hidden = NO;
	self.gridView.hidden = YES;
	//Setup operation queue to spin up non blocking execution thread.
	self.oppQueue = [[NSOperationQueue alloc] init];
	self.getMediaListOperation = [[GetMediaListOperation alloc] init];
	NSString *mediaAPI = [NSString stringWithFormat:@"%@action=getMediaList&class_id=1&start=0&limit=25&output=xml&show_total_view=1&collection_ids=%@&atoken=%@", MEDIA, theCollection.collection_id, ATOKEN ];
	self.getMediaListOperation.mediaApi =  mediaAPI;
	self.getMediaListOperation.delegate = self;
	[oppQueue addOperation:self.getMediaListOperation];
	[self.getMediaListOperation release];
	
}

-(void) updateTableWithCollection:(VmixCollection *) theCollection{
	
	[self.collectionsButton  setTitle:theCollection.name forState:UIControlStateNormal];
	[self.collectionsPopOver dismissPopoverAnimated:YES];
	//self.imageCache = nil;
	self.mediasArray = nil;
	
	[self.delegate updateTableWithCollection:theCollection];
	[self getMediaListForCollection:theCollection];
}


//Delegate method to comply with GetMediaListOperationDelegate
- (void)didFinishParsingMedia:(NSMutableArray *) mediaArray{
	
	
	[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
	self.mediasArray = mediaArray;
	self.collectionSpinner.hidden = YES;
	self.gridView.hidden = NO;
	[self performSelectorOnMainThread:@selector(reloadTheTableData) 
						   withObject:nil
						waitUntilDone:YES];
	
	
	
}

-(void) reloadTheTableData{
	
	[self.gridView reloadData];
	
}

- (void) viewDidUnload
{
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
    [_gridView release]; _gridView = nil;
}

- (void) dealloc
{

    [_gridView release];
    [super dealloc];
}


@end
